<template>
    <div class="account-list">
       <Pane>
           <template v-slot:title>
                <span>账号列表</span>
           </template>

           <template v-slot:content>
               <el-table
                :data="tableData"
                style="width: 100%"
                ref="multipleTable"
                @selection-change="handleSelectionChange"
                >
                    <!-- 全选列 -->
                    <el-table-column
                        type="selection"
                        width="55">
                    </el-table-column>
                   
                     <el-table-column
                        prop="id"
                        label="ID"
                        width="100">
                    </el-table-column>

                    <el-table-column
                        prop="account"
                        label="账号"
                        width="100">
                    </el-table-column>

                    <el-table-column
                        prop="userGroup"
                        label="用户组">
                    </el-table-column>
                    
                    <!-- 使用自定义表格内容 + 自定义过滤器，适合复杂的场景-->
                    <!-- <el-table-column
                        label="创建时间"
                        width="180">
                        <template slot-scope="scope">
                            {{scope.row.ctime|date}}
                        </template>
                    </el-table-column> -->
                     <el-table-column
                        prop="ctime"
                        :formatter="formateDate"
                        label="创建时间"
                        width="180">
                    </el-table-column>

                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" @click="editAccount(scope.row)">编辑</el-button>
                            <el-button
                            size="mini"
                            type="danger" @click="delAccount(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>

                </el-table>

                <div class="block page">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pageSize"
                        :total="totalNum"
                        :page-sizes="[10, 20, 30, 40]"
                        layout="total, sizes, prev, pager, next, jumper">
                    </el-pagination>
                </div>
                <!-- {{pageSize}}-{{currentPage}} -->
                
                <el-row class="opration">
                    <el-col :span="24">
                        <el-button @click="deleteAll" type="primary">批量删除</el-button>
                        <el-button @click="cancelAll()" type="danger">取消选择</el-button>
                    </el-col>
                </el-row>
                <!-- {{multipleSelection}}-{{ids}} -->
           </template>
       </Pane>
      
      <!-- dialog start -->
      <el-dialog
        title="编辑账号"
        :visible.sync="dialogVisible"
        width="30%">
        <!-- 内容 -->
       <el-form :model="account">
            <el-form-item label="账号" label-width="120px">
                <el-input v-model="account.name" autocomplete="off" style="width:225px"></el-input>
            </el-form-item>

            <el-form-item label="用户组" label-width="120px">
                <el-select v-model="account.group" placeholder="请选择用户组">
                    <el-option label="普通用户" value="普通用户"></el-option>
                    <el-option label="超级管理员" value="超级管理员"></el-option>
                </el-select>
            </el-form-item>
        </el-form>

        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveAccount">确 定</el-button>
        </span>
      </el-dialog>
      <!-- dialog end -->
    </div>
</template>

<script>
    import Pane from '@/components/Pane/Pane'
    import {getList,delAccount,delMoreAccount,updateAccount} from "@/api/account";//
    import moment from 'moment';

    export default {
        components:{
            Pane
        },
        data(){
            return {
                dialogVisible:false,//是否显示对话框
                tableData: [
                   /*  {
                       id:1,
                        date: '2016-05-02',
                        name: '王小虎',
                        address: '上海市普陀区金沙江路 1518 弄'
                    }, {
                        id:2,
                        date: '2016-05-04',
                        name: '王小虎',
                        address: '上海市普陀区金沙江路 1517 弄'
                    }, {
                        date: '2016-05-01',
                        name: '王小虎',
                        address: '上海市普陀区金沙江路 1519 弄'
                    }, {
                        date: '2016-05-03',
                        name: '王小虎',
                        address: '上海市普陀区金沙江路 1516 弄'
                    } */
                ],
                currentPage:1,//当前是第几页，默认是第一页
                pageSize:10,//每页显示几条数据
                totalNum:0,//总条数
                multipleSelection: [],//全选后的值数组
                account:{
                    name:"",
                    group:"",
                    id:"" //当前账号的id,提交修改的时候需要
                }
            }
        },
        computed:{
            //根据复选框中的数据对象，提取出id数组
            ids(){
                // return this.multipleSelection.map(item=>item.id)
                return this.multipleSelection.map((item)=>{return item.id})
            }
        },
        methods:{
            //分页相关
            handleSizeChange(val){
                console.log(`每页 ${val} 条`);
                // 当切换每页显示的条数的时候，保存一下大小
                this.pageSize = val;
                this.getAccountList();//获取分页数据
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                //当点击页码的时候，保存起来
                this.currentPage = val;
                this.getAccountList();//获取分页数据
            },
            //
            deleteAll() {
                //判断是否选择
                if(this.ids.length ==0){
                    this.$message({
                        message: '请勾选要删除的数据!',
                        type: 'warning'
                    });
                    return;
                }

                //确认
                this.$confirm(
                    "确定删除所选的内容吗?",
                    "提示",
                     {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(async ()=>{
                    //确定
                    console.log('确定')
                    let ids_str = JSON.stringify(this.ids); //转为字符串(对象转为字符串):'[1,2,3]'
                    // console.log(typeof ids_str);

                    //发请求，删除数据
                    let result = await delMoreAccount({ids:ids_str});
                    let {code} = result;//解构赋值，到辩论中
                    // console.log(result,code,msg)
                    if(code == 0){
                        //成功，刷新页面
                        this.getAccountList();
                    }
                }).catch(()=>{
                    //取消
                    console.log('取消')
                })
            },
            cancelAll(){
                this.$refs.multipleTable.clearSelection();
            },
            handleSelectionChange(val) {
                //复选框发生变化后，执行
                this.multipleSelection = val;
            },
            async getAccountList(){
                var currentPage = this.currentPage; //当前是第几页，1,2,3
                var pageSize = this.pageSize;//每页条数

                let list = await getList({currentPage,pageSize}); //获取列表
                console.log(list)
                /* list.then((res)=>{
                    console.log(res)
                })
                .catch(err=>{
                    console.lg(err)
                }) */
                //渲染列表
                this.tableData = list.data||[];
                //总数
                this.totalNum = list.total;
            },
            formateDate(row, column, cellValue, index){
                if(cellValue){
                    return moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
                }
                return '-';
            },
            delAccount(id){
                console.log(id)
                this.$confirm(
                    "确定要删除吗?",
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(async res=>{
                    console.log("确定del")
                    //选择确定，发请求（api/account.js定义ajax工具方法）
                    let result = await delAccount({id})
                    console.log(result)
                    if(result.code == 0){
                        //成功，获取列表数据
                        this.getAccountList();
                    }

                }).catch(cancel=>{
                    console.log('取消了')
                })
            },
            editAccount(row){
                //1.显示对话框
                //2.显示数据到表单
                this.dialogVisible = true;
                console.log(row)
                this.account.name = row.account;
                this.account.group = row.userGroup;
                this.account.id = row.id;
            },
            async saveAccount(){
                //1.验证表单是否通过
                //2.发请求，保存数据
                let data = {
                    id:this.account.id,
                    account:this.account.name,
                    userGroup:this.account.group
                }
                let result = await updateAccount(data);
                let {code} = result;
                console.log(result)
                if(code == 0){
                    //3.成功，关闭提示框
                    this.dialogVisible = false;
                    // this.$router.push("/account/account-list")
                    this.getAccountList();//刷新数据
                }
            }
        },
        created(){
            this.getAccountList();//页面载入的时候，获取列表数据
        }
    }
</script>

<style lang="less" scoped>
.account-list{
    .page,.opration{
        margin-top: 15px;
    }
}
</style>